Completed
Push — master ( d362a9...56faa4 )
by Mark
14s queued 11s
created

HasMany   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 48
dl 0
loc 65
rs 10
c 0
b 0
f 0
wmc 12

4 Functions

Rating   Name   Duplication   Size   Complexity  
B getRelationalFields 0 3 6
A setParentProperties 0 20 1
A setName 0 8 1
A getValueByParentKey 0 5 4
1
import Relation from "../Relation.js";
2
import {ModelStaticInterface} from "../../../JeloquentInterfaces";
3
import Collection from "../../Collection";
4
import ForeignKey from "../Field/ForeignKey";
5
6
/**
7
 *
8
 */
9
export default class HasMany extends Relation {
10
11
    localKey: string;
12
13
    constructor(model: ModelStaticInterface, foreignKey: string, localKey: string) {
14
        super(model, foreignKey);
15
        this.localKey = localKey ?? 'id';
16
    }
17
18
    get count(): number {
19
        const indexes = globalThis.Store.database().indexes(this.model.className);
20
        return indexes.get(this.foreignKey).get(this.$parent.primaryKey)?.size ?? 0;
21
    }
22
23
    get originalValue(): unknown {
24
        return this.getValueByParentKey('originalPrimaryKey');
25
    }
26
27
    get value(): unknown {
28
        return this.getValueByParentKey('primaryKey');
29
    }
30
31
    getRelationalFields():Array<ForeignKey> {
32
        return [];
33
    }
34
35
    setName(): HasMany {
36
        const parentClassName = this.$parent.snakeCaseClassName;
37
        const modelClassName = this.model.snakeCaseClassName;
38
39
        this.foreignKey = `${parentClassName}_id`;
40
        this.$name = `${modelClassName}s`;
41
        return this;
42
    }
43
44
    protected getValueByParentKey(parentProperty): Collection {
45
        const keyIndex = this.model.getIndexByKey(this.foreignKey);
46
        return globalThis.Store.database().find(this.model.className,
47
            [...keyIndex.get(this.$parent[parentProperty])?.values() ?? []]
48
        );
49
    }
50
51
    protected setParentProperties(): HasMany {
52
        super.setParentProperties();
53
54
        Object.defineProperty(this.$parent,
55
            `${this.name}Count`, {
56
                get: () => {
57
                    return this.count;
58
                },
59
            }
60
        );
61
62
        Object.defineProperty(this.$parent,
63
            `has${this.model.className}s`, {
64
                get: () => {
65
                    return this.count > 0;
66
                },
67
            }
68
        );
69
        return this;
70
    }
71
}